package com.example.journeyreserve

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.journeyreserve.model.*
import com.example.journeyreserve.network.JourneyResponseService
import com.example.journeyreserve.network.ReservationResponseService
import com.example.journeyreserve.network.ServiceCreator
import com.example.journeyreserve.network.TestResponseService
import com.example.journeyreserve.ui.theme.JourneyReserveTheme
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JourneyReserveTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    showButtonTest()
                }
            }
        }









    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
@Preview
fun showButtonTest(){

    /**\
     * 所有会变的变量都要用remember！！！
     */
    val resBuiler = StringBuilder("test")

    var reserveId by remember {
        mutableStateOf("0")
    }
    var userName by remember {
        mutableStateOf("SpreadZhao")
    }
    var reserveHotelLocation by remember {
        mutableStateOf("ShangHai")
    }
    var reserveFlightNum by remember{
        mutableStateOf("3U8595")
    }
    var reserveBusLocation by remember {
        mutableStateOf("Harbin")
    }

    val num = remember {
        mutableStateOf(0)
    }
    var textRes by remember {
        mutableStateOf("Nothing")
    }

    val testResponseService = ServiceCreator.create<TestResponseService>()
    val reserver = ServiceCreator.create<ReservationResponseService>()
    val journeyShower = ServiceCreator.create<JourneyResponseService>()

    LazyColumn {
        item {
            Row(
                modifier = Modifier
                    .wrapContentHeight()
                    .wrapContentWidth()
            ) {

                /**
                 * Buttons
                 */
                Column(
                    modifier = Modifier
                        .width(Dp(200F))
                        .wrapContentHeight(),
//        verticalArrangement = Arrangement.Center,
//        horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    val context = LocalContext.current

                    /**
                     * test Plus One Btn
                     */
                    Button(
                        onClick = {
                            Toast.makeText(context, "test button in compose", Toast.LENGTH_SHORT).show()
                            num.value += 1
                            Log.d("jnytst", "num: $num")
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue))
                    ) {
                        Text(text = "PlusOne")
                    }

                    /**
                     * testBtn
                     */
                    Button(
                        onClick = {
                            resBuiler.clear()
                            Toast.makeText(context, "test button in compose", Toast.LENGTH_SHORT).show()
                            testResponseService.test().enqueue(object: Callback<TestResponse>{
                                override fun onResponse(call: Call<TestResponse>, response: Response<TestResponse>) {
                                    val testResponse = response.body()
                                    if(testResponse != null){
                                        if(testResponse.success){
                                            Log.d("jnytst", "test response sussess!")
//                                val list = testResponse.list
//                                for(elem in list){
//                                    Log.d("jnytst", "location: ${elem.location}")
//                                }
                                            for(elem in testResponse.list){
                                                resBuiler.append(elem.location).append("\n")
                                            }
                                            textRes = resBuiler.toString()
                                        }else{
                                            Log.d("jnytst", "test response fail!")
                                        }
                                    }else{
                                        Log.d("jnytst", "response is null!")
                                    }
                                }

                                override fun onFailure(call: Call<TestResponse>, t: Throwable) {
                                    t.printStackTrace()
                                    Log.d("jnytst", "on failure!")
                                }
                            })
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue))
                    ) {
                        Text(text = "test")
                    }

                    /**
                     * Reserve Hotel Btn
                     */
                    Button(
                        onClick = {
                            resBuiler.clear()
//                reserveHotelService.reserveHotel(Reservation(reserveHotelId, userName, 3))
                            Log.d("jnytst", "new round, reserveId: $reserveId")
                            val newId = getWholeId(reserveId, reserveHotelLocation)
                            Log.d("jnytst", "newId: $newId")
                            reserver.reserveHotel(Reservation(newId, userName, 3)).enqueue(object : Callback<ReservationResponse>{
                                override fun onResponse(
                                    call: Call<ReservationResponse>,
                                    response: Response<ReservationResponse>
                                ) {
                                    val rsvResponse = response.body()
                                    if(rsvResponse != null){
                                        if(rsvResponse.success){
                                            Log.d("jnytst", "reserve is success")
                                            resBuiler
                                                .appendLine("op: " + rsvResponse.op)
                                                .appendLine("msg: " + rsvResponse.msg)
                                                .appendLine("dataTime: " + rsvResponse.dateTime)
                                            textRes = resBuiler.toString()
                                            var id = reserveId.toInt()
                                            id++
                                            reserveId = id.toString()

                                            Log.d("jnytst", "reserveId: $reserveId")
                                        }else{
                                            Log.d("jnytst", "reserve is fail.")
                                            textRes = "reserve fail!"
                                        }
                                    }else{
                                        Log.d("jnytst", "reserve response is null")
                                        textRes = "response is null"

                                    }
                                }

                                override fun onFailure(call: Call<ReservationResponse>, t: Throwable) {
                                    t.printStackTrace()
                                    Log.d("jnytst", "reserve on failure")
                                    textRes = "response on failure"
                                }
                            })
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.White))
                    ) {
                        Text(text = "ReserveHotel")
                    }

                    /**
                     * Reserve Flight Btn
                     */
                    Button(
                        onClick = {
                            resBuiler.clear()
                            val newId = getWholeId(reserveId, reserveFlightNum)
                            reserver.reserveFlight(Reservation(newId, userName, 1)).enqueue(object: Callback<ReservationResponse>{
                                override fun onResponse(
                                    call: Call<ReservationResponse>,
                                    response: Response<ReservationResponse>
                                ) {
                                    val fltResponse = response.body()
                                    if(fltResponse != null){
                                        if(fltResponse.success){
                                            resBuiler
                                                .appendLine("op: " + fltResponse.op)
                                                .appendLine("msg: " + fltResponse.msg)
                                                .appendLine("dataTime: " + fltResponse.dateTime)
                                            textRes = resBuiler.toString()
                                            var id = reserveId.toInt()
                                            id++
                                            reserveId = id.toString()
                                        }else{
                                            textRes = "reserve fail!"
                                        }
                                    }else{
                                        textRes = "response is null"
                                    }
                                }

                                override fun onFailure(call: Call<ReservationResponse>, t: Throwable) {
                                    t.printStackTrace()
                                    textRes = "response on failure"
                                }
                            })
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Cyan))
                    ) {
                        Text(text = "ReserveFlight")
                    }

                    /**
                     * Reserve Bus Btn
                     */
                    Button(
                        onClick = {
                            resBuiler.clear()
                            val newId = getWholeId(reserveId, reserveBusLocation)
                            reserver.reserveBus(Reservation(newId, userName, 2)).enqueue(object: Callback<ReservationResponse>{
                                override fun onResponse(
                                    call: Call<ReservationResponse>,
                                    response: Response<ReservationResponse>
                                ) {
                                    val busResponse = response.body()
                                    if(busResponse != null){
                                        if(busResponse.success){
                                            resBuiler
                                                .appendLine("op: " + busResponse.op)
                                                .appendLine("msg: " + busResponse.msg)
                                                .appendLine("dataTime: " + busResponse.dateTime)
                                            textRes = resBuiler.toString()
                                            var id = reserveId.toInt()
                                            id++
                                            reserveId = id.toString()
                                        }
                                    }
                                }

                                override fun onFailure(
                                    call: Call<ReservationResponse>,
                                    t: Throwable
                                ) {
                                    TODO("Not yet implemented")
                                }
                            })
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Cyan))
                    ) {
                        Text(text = "ResersveBus")
                    }

                    /**
                     * Show Journey Btn
                     */
                    Button(
                        onClick = {
                            resBuiler.clear()
                            journeyShower.showJourney(userName).enqueue(object : Callback<JourneyResponse>{
                                override fun onResponse(
                                    call: Call<JourneyResponse>,
                                    response: Response<JourneyResponse>
                                ) {
                                    val jnyResponse = response.body()
                                    if(jnyResponse != null){
                                        if(jnyResponse.success){
                                            resBuiler
                                                .appendLine("op: " + jnyResponse.op)
                                                .appendLine("msg: " + jnyResponse.msg)
                                                .appendLine("People: " + jnyResponse.people)
                                                .appendLine("==========")
                                            for(elem in jnyResponse.journeys){
                                                resBuiler
                                                    .appendLine("Flight Number: ${elem.flightNum}")
                                                    .appendLine("From City: ${elem.fromCity}")
                                                    .appendLine("Arrive City: ${elem.arivCity}")
                                                    .appendLine("==========")
                                            }
                                            textRes = resBuiler.toString()
                                        }else{
                                            textRes = "show journey fail!"
                                        }
                                    }else{
                                        textRes = "response is null"
                                    }
                                }

                                override fun onFailure(call: Call<JourneyResponse>, t: Throwable) {
                                    t.printStackTrace()
                                    textRes = "response on failure"
                                }
                            })
                        },
                        modifier = Modifier.padding(all = Dp(10F)),
                        enabled = true,
                        border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Red))
                    ) {
                        Text(text = "Show ${userName}'s Journey", fontSize = 10.sp)
                    }



                } // end Column Buttons


                /**
                 * Outlined TextFields
                 */
                Column(
                    modifier = Modifier
                        .wrapContentWidth()
                        .wrapContentHeight()
                ) {
                    OutlinedTextField(
                        value = userName,
                        onValueChange = {userName = it},
                        label = { Text("User Name") }
                    )
                    OutlinedTextField(
                        value = reserveId,
                        onValueChange = {reserveId = it},
                        label = { Text("Reserve Id") }
                    )
                    OutlinedTextField(
                        value = reserveFlightNum,
                        onValueChange = { reserveFlightNum = it },
                        label = { Text("Flight Number") }
                    )
                    OutlinedTextField(
                        value = reserveHotelLocation,
                        onValueChange = { reserveHotelLocation = it },
                        label = { Text("Hotel Location") }
                    )
                    OutlinedTextField(
                        value = reserveBusLocation,
                        onValueChange = { reserveBusLocation = it },
                        label = { Text("Bus Location") }
                    )
                }

            }
        }

        item {
            Text(text = num.value.toString())
            Text(text = textRes)
        }

    }







}

fun getWholeId(id: String, name: String): String{
//    val idSection = id.subSequence(0, 3)
//    var idNum = idSection.toString().toInt()
//    idNum++;
//    return idNum.toString() + id.substring(4)
    Log.d("jnytst", "in getNextId, id is: $id")
    return String.format("%04d", id.toInt()) + name
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

//@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    JourneyReserveTheme {
        Greeting("Android")
    }
}